package cn.gson.boot.model.service;

import cn.gson.boot.model.dao.*;
import cn.gson.boot.model.mapper.KehuMapper;
import cn.gson.boot.model.pojos.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional(rollbackFor = Exception.class)
public class KehuService {
    @Autowired
    KehuDao kehuDao;//客户dao

    @Autowired
    ContactsDao contactsDao;//联系人dao

    @Autowired
    HebingDao hebingDao;//合并表dao

    @Autowired
    HeTongDao heTongDao;//合同表dao

    @Autowired
    DinDanDao dinDanDao;//订单表dao

    @Autowired
    BusinessDao businessDao;//出差dao

    @Autowired
    KehuMapper kehuMapper;
    @Autowired
    UserDao userDao;

    //模糊查询和分页查询
    public List<Kehu> allKehus(String kType,String Kname,String kSmzq,int empId){
        return kehuMapper.allKehus(kType,Kname,kSmzq,empId);
    }

    public List<KehuVo> suoyoukehu(){
        return kehuMapper.suoyoukehu();
    }

    //查询客户名称是否重复
    public int kehuchongfu(String kName){
        List<Kehu>  kelist=kehuMapper.kehuchongfu(kName);
        if(kelist.size()>0){
            return  1;
        }else{
            return  0;
        }
    }

    //中国地图查询数据
    public List<Kehu> dituKehus(int empId){
        return kehuMapper.dituKehus(empId);
    }

    //查客户连表客户联系人和员工详情查询
    public List<Kehu> xqKehus(Integer kId){
        return kehuMapper.xqKehus(kId);
    }

    //查客户查询
    public Kehu xq2Kehus(Integer kId){
        return kehuMapper.xq2Kehus(kId);
    }

    //时间线--全部
    public List<Kehu> timeSelect(Integer kid){
        return kehuMapper.timeSelect(kid);
    }

    //时间线--销售机会
    public List<Sales> allshangji(Integer kId){
        return kehuMapper.allshangji(kId);
    }

    //时间线--客户关怀
    public List<Caring> allcaring(Integer kId){
        return kehuMapper.allcaring(kId);
    }

    //时间线--维修工单
    public List<Weixiugongdan> allwxiu(Integer kId){
        return kehuMapper.allwxiu(kId);
    }

    //时间线--合同
    public List<Hetong> allhetong(Integer kId){
        return kehuMapper.allhetong(kId);
    }

    //时间线--回款
    public List<Huikuan> allhuikuan(Integer kId){
        return kehuMapper.allhuikuan(kId);
    }

    //时间线--退货
    public List<Tuihuo> alltuihuo(Integer kId){
        return kehuMapper.alltuihuo(kId);
    }

    //时间线--交付记录
    public List<Jiaofujilu> alljiaofujlu(Integer kId){
        return kehuMapper.alljiaofujlu(kId);
    }

    //新增和修改
    public  String  addKehu(KehuandConVo kehuandConVo ,HttpSession session){
        System.out.println("确认按钮");
        Date date = new  Date();
        Timestamp tt = new Timestamp(date.getTime());
        int id = kehuandConVo.getkId();
        System.out.println("客户编号："+id);
        User us =  (User) session.getAttribute("user");
        System.err.println("客户界面新增客户的员工id:"+us.getEmpId());
        System.err.println("传的客户"+kehuandConVo.getkName());
        if(id==0){
                System.out.println("开始新增");
                int phone = contactsDao.findKehuByMphone2(kehuandConVo.getcMphone().toString(),kehuandConVo.getcWphone().toString());
                if (phone >0){
                    return "联系人手机号重复！";
                }
                Kehu k1 = new Kehu();
                User user = new User(us.getEmpId());
                k1.setkType("客户");
                k1.setEmpId(user);
                k1.setkSmzq("潜在");
                k1.setkCsjian(tt);
                k1.setkXsjian(tt);
                k1.setkTchi(0);
                k1.setkSheng(kehuandConVo.getkSheng());
                k1.setkShi(kehuandConVo.getkShi());
                k1.setkQu(kehuandConVo.getkQu());
                k1.setkGongsid(kehuandConVo.getkGongsid());
                k1.setkZtai(1);
                k1.setkJname(kehuandConVo.getkJname());
                k1.setkName(kehuandConVo.getkName());
                k1.setkLaiy(kehuandConVo.getkLaiy());
                k1.setkBeizhu(kehuandConVo.getkBeizhu());
                kehuDao.save(k1);
                //新增联系人
                Contacts contacts = new Contacts();
                contacts.setcCjjian(tt);
                contacts.setcGxjian(tt);
                contacts.setkId(k1);
                contacts.setcZtai(1);
                contacts.setcSex("男");
                contacts.setcName(kehuandConVo.getcName());
                contacts.setcWphone(kehuandConVo.getcWphone());
                contacts.setcMphone(kehuandConVo.getcMphone());
                contactsDao.save(contacts);
        }else{
            //修改客户
            System.out.println("开始修改");
            //修改客户名称  客户简称  客户种类type
            Kehu kehu2 = kehuDao.findById(id).get();//找到修改的用户
            //把界面的数据赋值到数据库
            kehu2.setkSmzq(kehuandConVo.getkSmzq());//生命周期
            kehu2.setkName(kehuandConVo.getkName());//客户名称
            kehu2.setkJname(kehuandConVo.getkJname());//客户简称
            kehu2.setkType(kehuandConVo.getkType());//客户来源
            kehu2.setkXsjian(kehuandConVo.getkXsjian());//更新时间（签约时间）
            kehu2.setkSheng(kehuandConVo.getkSheng());//省
            kehu2.setkShi(kehuandConVo.getkShi());//市
            kehu2.setkQu(kehuandConVo.getkQu());//区
            kehu2.setkGongsid(kehuandConVo.getkGongsid());//公司地址
            kehuDao.save(kehu2);//执行修改
        }
        return "success";
    }

    //客户导入(新增)(验证判断)
    public String importCustomer(String kehu,HttpSession session) throws ParseException {
        System.out.println("进来了");
        JSONObject object = (JSONObject) JSONObject.parse(kehu);
        List list = object.getObject("kehu",List.class);
        JSONArray array = (JSONArray) JSONArray.parseArray(String.valueOf(list));
        //登录进来的用户（保存）
        User us =  (User) session.getAttribute("user");
        System.err.println("客户界面导入客户的员工id:"+us.getEmpId());
        //查询所有的客户
        List<Kehu> all = (List<Kehu>)kehuDao.findAll();
        JSONObject jsonObject =null;
        //收集要返回的验证返回到前端 使前端判断
        List<JSONObject> listMap = new ArrayList<>();

        String allResult="";//返回数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Integer Ok = 0;//成功数
        Integer No = 0;//失败数
            for (int i = 0; i < array.size(); i++) {
                System.out.println("进来新增了");
                jsonObject = (JSONObject)array.get(i);//前端导入的数据

                int code = 0;//初始化
                //客户名称判断
                if (null == jsonObject.getString("kName")  || jsonObject.getString("kName").trim().equals("")){
                    jsonObject.put("kNamebunull","客户姓名不能为空！");
                    code++;
                }else{
                    //客户名称判断是否重复
                    int kehuCount = kehuDao.findKehuByName(jsonObject.getString("kName"));
                    if (kehuCount > 0){
                        jsonObject.put("kNamechongfu","客户姓名重复！");
                        code++;
                    }
                }

                //来源判断
                if (null == jsonObject.getString("kLaiy")  || jsonObject.getString("kLaiy").trim().equals("")){
                    jsonObject.put("kLaiybunull","来源不能为空！");
                    code++;
                }else{
                    if(!jsonObject.getString("kLaiy").trim().equals("电话来访") &&
                        !jsonObject.getString("kLaiy").trim().equals("客户介绍") &&
                        !jsonObject.getString("kLaiy").trim().equals("互联网")     &&
                        !jsonObject.getString("kLaiy").trim().equals("独立开发") &&
                        !jsonObject.getString("kLaiy").trim().equals("媒体宣传") &&
                        !jsonObject.getString("kLaiy").trim().equals("其他")){
                            jsonObject.put("kLaiygeshi","来源格式有误！");
                            code++;
                    }
                }

                //种类判断
                if (null == jsonObject.getString("kType")  || jsonObject.getString("kType").trim().equals("")){
                    jsonObject.put("kTypebunull","种类不能为空！");
                    code++;
                }else{
                    if(!jsonObject.getString("kType").trim().equals("客户")
                        && !jsonObject.getString("kType").trim().equals("供应商")
                        && !jsonObject.getString("kType").trim().equals("合作伙伴")
                        && !jsonObject.getString("kType").trim().equals("媒体")
                        && !jsonObject.getString("kType").trim().equals("其他") ){
                            jsonObject.put("kTypegeshi","种类格式有误！");
                            code++;
                    }
                }

                //客户联系人判断
                if (null == jsonObject.getString("cName")  || jsonObject.getString("cName").trim().equals("")){
                    jsonObject.put("cNamebunull","联系人姓名不能为空！");
                    code++;
                }

                //客户联系人移动电话判断
                if (null == jsonObject.getString("cMphone")  || jsonObject.getString("cMphone").trim().equals("")){
                    jsonObject.put("cMphonebunull","客户联系人移动电话不能为空！");
                    code++;
                }else{
                    String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
                    Pattern p = Pattern.compile(regExp);
                    Matcher m = p.matcher(jsonObject.getString("cMphone"));
                    if(!m.matches()){
                        jsonObject.put("cMphonebunull","客户联系人移动电话格式错误！");
                        code++;
                    }
                    //客户联系人手机号判断是否重复
                    int contactsCount = contactsDao.findKehuByMphone(jsonObject.getString("cMphone"));
                    if(contactsCount>0){
                        jsonObject.put("cMphonechongfu","客户联系人电话重复！");
                        code++;
                    }
                }

                //联系人性别判断
                if (null == jsonObject.getString("cSex")  || jsonObject.getString("cSex").trim().equals("")){
                    jsonObject.put("cSexbunull","联系人性别不能为空！");
                    code++;
                }else{
                    if(!jsonObject.getString("cSex").equals("男") &&  !jsonObject.getString("cSex").equals("女")){
                        jsonObject.put("cSexbunull","联系人性别格式错误！");
                        code++;
                    }
                }
                //地址判断
                if (null == jsonObject.getString("kSheng")  || jsonObject.getString("kSheng").trim().equals("")||
                        null == jsonObject.getString("kShi")  || jsonObject.getString("kShi").trim().equals("")||
                        null == jsonObject.getString("kQu")  || jsonObject.getString("kQu").trim().equals("")||
                        null == jsonObject.getString("kGongsid")  || jsonObject.getString("kGongsid").trim().equals("")){
                    jsonObject.put("cSexbunull","地址不能为空！");
                    code++;
                }

                if (code > 0){
                    No++;
                    listMap.add((jsonObject));
                    continue;
                }else{
                    //判断成功进行新增
                    Kehu kehu1 = new Kehu();
                    Date date = new Date();
                    Timestamp tt = new Timestamp(date.getTime());
                    User user = new User(us.getEmpId());
                    kehu1.setkJname(jsonObject.getString("kJname"));
                    kehu1.setkName(jsonObject.getString("kName"));
                    kehu1.setkLaiy(jsonObject.getString("kLaiy"));
                    kehu1.setkBeizhu(jsonObject.getString("kBeizhu"));
                    kehu1.setkSheng(jsonObject.getString("kSheng"));
                    kehu1.setkShi(jsonObject.getString("kShi"));
                    kehu1.setkQu(jsonObject.getString("kQu"));
                    kehu1.setkGongsid(jsonObject.getString("kGongsid"));
                    kehu1.setEmpId(user);//保存的用户 存进去
                    System.out.println("----1"+jsonObject.getString("kGongsid"));
                    kehu1.setkSmzq("潜在");
                    kehu1.setkType(jsonObject.getString("kType"));
                    kehu1.setkZtai(1);
                    kehu1.setkCsjian(tt);
                    kehu1.setkXsjian(tt);
                    kehuDao.save(kehu1);
                    Contacts contacts = new Contacts();
                    contacts.setkId(kehu1);
                    contacts.setcZtai(1);
                    contacts.setcSex(jsonObject.getString("cSex"));
                    contacts.setcName(jsonObject.getString("cName"));
                    contacts.setcMphone(jsonObject.getLong("cMphone"));
                    contacts.setcSheng(jsonObject.getString("kSheng"));
                    contacts.setcShi(jsonObject.getString("kShi"));
                    contacts.setcQu(jsonObject.getString("kQu"));
                    contacts.setcHomed(jsonObject.getString("kHomed"));
                    contactsDao.save(contacts);
                    Ok++;
                }
            }
            Map<String,Object> resultMap = new HashMap<>();
            if (listMap != null && listMap.size() > 0){
                resultMap.put("OK",Ok);
                resultMap.put("NO",No);
                resultMap.put("TOTAL",array.size());
                resultMap.put("Result",listMap);
            }else {
                allResult="success";
                resultMap.put("Result",allResult);
            }
        return JSONObject.toJSONString(resultMap);
    }

    //获客详情界面加为新客户（新增）
    public String addhuokehu(KehuandConVo kehuandConVo , HttpSession session){
        System.out.println("新增了");
        int kehuByMphone = contactsDao.findKehuByMphone2(kehuandConVo.getcMphone().toString(),kehuandConVo.getcWphone().toString());
        if (kehuByMphone >0){
            return "联系人手机号重复！";
        }
        Date date = new  Date();
        Timestamp tt = new Timestamp(date.getTime());
        User us =  (User) session.getAttribute("user");
        System.err.println("获客加为客户的员工id:"+us.getEmpId());
        //新增客户信息
        Kehu k2 = new Kehu();
        User user = new User(us.getEmpId());
        k2.setkType("客户");k2.setEmpId(user);
        k2.setkSmzq("潜在");k2.setkCsjian(tt);
        k2.setkXsjian(tt);
        k2.setkZtai(1); k2.setkTchi(0);
        k2.setkName(kehuandConVo.getkName());
        k2.setkLaiy(kehuandConVo.getkLaiy());
        k2.setkBeizhu(kehuandConVo.getkBeizhu());
        k2.setkSheng(kehuandConVo.getkSheng());//省
        k2.setkShi(kehuandConVo.getkShi());//市
        k2.setkQu(kehuandConVo.getkQu());//区
        k2.setkGongsid(kehuandConVo.getkGongsid());//公司名称
        System.out.println("省："+kehuandConVo.getkSheng());
        kehuDao.save(k2);
        //新增客户联系人信息
        Contacts c2 = new Contacts();
        c2.setkId(k2);//对应客户id
        c2.setcZtai(1);//删除状态
        c2.setcWphone(kehuandConVo.getcWphone());//手机号码
        c2.setcMphone(kehuandConVo.getcMphone());//电话号码
        c2.setcName(kehuandConVo.getcName());//客户名称
        c2.setcQQ(kehuandConVo.getcQQ());//qq
        c2.setcWX(kehuandConVo.getcWX());//微信
        c2.setcSex("男");
        contactsDao.save(c2);
        return "success";
    }

    //逻辑删除
    public void deleteKehu(int id ){
        System.out.println("开始删除");
        Kehu k3 = kehuDao.findById(id).get();//找到删除的客户id
        System.out.println("id"+id);
        k3.setkZtai(0);
        k3.setkSmzq("失效");
        kehuDao.save(k3);
        //联系人的删除
        List<Contacts> contacts = contactsDao.contactscha(id);//通过
        for (int i=0 ;i<contacts.size();i++){
            System.err.println("删除联系人");
            contactsDao.delContacts(id);
        }
    }

    //客户合并
    public void Kehuhebing(Integer Aid,Integer Bid,HttpSession session){
        System.out.println("开始合并");System.out.println("被合并id:"+Aid);System.out.println("合并id:"+Bid);
        Date date = new  Date();
        Timestamp tt = new Timestamp(date.getTime());
        Kehu k1 = kehuDao.findById(Aid).get();//被合并的客户id
        //联系人的合并
        List<Contacts> contacts = contactsDao.contactscha(Aid);
        for (int i=0 ;i<contacts.size();i++){
            System.err.println("合并联系人");
            contactsDao.kehuhebing(Bid,Aid);
        }
        //合同的合并
        List<Hetong> hetongs = heTongDao.hetongcha(Aid);
        for (int s=0 ;s<hetongs.size();s++){
            System.err.println("合并合同");
            heTongDao.kehuhebing(Bid,Aid);
        }
        //订单的合并
        List<Dingdan> dingdans = dinDanDao.dingdancha(Aid);
        for (int a=0 ;a<dingdans.size();a++){
            System.err.println("合并订单");
            dinDanDao.kehuhebing(Bid,Aid);
        }
       //出差的合并
        List<Business> businesses = businessDao.businesscha(Aid);
        for (int a=0 ;a<businesses.size();a++){
            System.err.println("合并出差");
            businessDao.kehuhebing(Bid,Aid);
        }
        //合并表的新增
        Kehu bkehu = kehuDao.findById(Aid).get();//找到被合并id
        Kehu hkehu = kehuDao.findById(Bid).get();//找到合并id
        Hebing hebing = new Hebing();
        User us =  (User) session.getAttribute("user");
        User user = new User(us.getEmpId());
        hebing.sethShijian(tt);
        hebing.setEmpId(user);
        hebing.sethMingxi("将客户:"+"【"+bkehu.getkName()+"】"+"合并进入客户:"+"【"+hkehu.getkName()+"】"+","+"【"+bkehu.getkName()+"】"+"清除");
        hebingDao.save(hebing);
        k1.setkZtai(0);
        kehuDao.save(k1);
    }

    //客户回收站（查询）
    public List<Kehu> Kehushui(){
        return kehuMapper.Kehushui();
    }

    //客户回收站（还原）修改
    public void huanyuan(Integer id,HttpSession session){
        System.out.println("开始还原");
        Kehu k4 = kehuDao.findById(id).get();//找到删除的客户id
        System.out.println("id"+id);
        User us =  (User) session.getAttribute("user");
        User user = new User(us.getEmpId());
        System.err.println("客户回收站界面的员工id:"+us.getEmpId());
        k4.setkZtai(1);
        k4.setkSmzq("潜在");
        k4.setEmpId(user);//修改他还原之后的是当前的登陆人
        kehuDao.save(k4);
        //联系人的删除
        List<Contacts> contacts = contactsDao.contactscha(id);//通过
        for (int i=0 ;i<contacts.size();i++){
            System.err.println("还原联系人");
            contactsDao.hyContacts(id);
        }
    }

    //统计图客户类型查询
    public Map<String,Object> kehuleixing(int empId){
        Map<String,Object> map = new HashMap<>();
        Integer  k1 =  kehuMapper.kehuleixing("潜在",empId);
        Integer  k2 =  kehuMapper.kehuleixing("签约",empId);
        Integer  k3 =  kehuMapper.kehuleixing("重复购买",empId);
        Integer  k4 =   kehuMapper.kehuleixing("失效",empId);
        List<Integer> sj = new ArrayList<>();
        sj.add(k1);
        sj.add(k2);
        sj.add(k3);
        sj.add(k4);
        List<String> mz = new ArrayList<>();
        mz.add("潜在");
        mz.add("签约");
        mz.add("重复购买");
        mz.add("失效");
        map.put("sj",sj);
        map.put("mz",mz);
        return map;
    }

    //统计图客户所有者
    public Map<String,Object> kehufuzeren(int empId){
        List<User> emp = kehuMapper.em(empId);
        Map<String,Object> map = new HashMap<>();
        List<Integer> sj = new ArrayList<>();
        List<String> mz = new ArrayList<>();
        for(int i=0;i<emp.size();i++){
            sj.add(kehuDao.kehufuzeren(emp.get(i).getEmpId()));
            mz.add(emp.get(i).getEmpName());
        }

        //颜色
        List<String> ys = new ArrayList<>();
        mz.add("#5fbeaa");
        mz.add("#5fbeaa");
        mz.add("#6c85bd");
        mz.add("#34d3eb");
        mz.add("#ebeff2");

        map.put("sj",sj);
        map.put("mz",mz);
        map.put("ys",ys);
        return map;
    }

    //统计图查询每个月客户创建数量
    public Map<String,Object> kehucj(int empId){
        Map<String,Object> map = new HashMap<>();
        List<Integer> sj = new ArrayList<>();//数量
        String str = null;
        DateFormat df =  new SimpleDateFormat("yyyy");
        String nian =  df.format(new Date());
        //循环12月
        for(int i = 1;i <= 12;i++){
            if(i<10){
                str = nian + "-0"+i;
            }else {
                str = nian + "-"+i;
            }
            sj.add(kehuMapper.quanKehus("%"+str+"%",empId));
        }
        map.put("sj",sj);
        return map;
    }
}
